/**
 * 权限管理工具
 */

class PermissionManager {
  /**
   * 请求存储权限
   * @param {Function} callback 权限获取成功回调
   */
  static requestStoragePermission(callback) {
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity()
      const Context = plus.android.importClass('android.content.Context')
      const ContextCompat = plus.android.importClass('androidx.core.content.ContextCompat')
      const ActivityCompat = plus.android.importClass('androidx.core.app.ActivityCompat')
      const Manifest = plus.android.importClass('android.Manifest')
      const Build = plus.android.importClass('android.os.Build')
      
      console.log('Android SDK版本:', Build.VERSION.SDK_INT)
      
      // Android 6.0+才需要动态权限
      if (Build.VERSION.SDK_INT < 23) {
        console.log('Android版本低于6.0，无需动态权限')
        callback(true)
        return
      }
      
      // 检查是否已有权限
      const PERMISSION_GRANTED = 0 // PackageManager.PERMISSION_GRANTED
      let hasWritePermission = false
      let hasReadPermission = false
      
      try {
        hasWritePermission = ContextCompat.checkSelfPermission(main, Manifest.permission.WRITE_EXTERNAL_STORAGE) === PERMISSION_GRANTED
        hasReadPermission = ContextCompat.checkSelfPermission(main, Manifest.permission.READ_EXTERNAL_STORAGE) === PERMISSION_GRANTED
      } catch (permError) {
        console.log('权限检查失败:', permError)
        // 如果权限检查失败，直接调用callback
        callback(false)
        return
      }
      
      if (hasWritePermission && hasReadPermission) {
        console.log('存储权限已获取')
        // 保存权限状态
        uni.setStorageSync('storage_permission_granted', true)
        callback(true)
        return
      }
      
      // 请求权限
      console.log('需要请求存储权限')
      uni.showModal({
        title: '权限申请',
        content: '为了保存下载的文件，需要访问存储空间权限。\\n\\n请在弹出的权限申请中点击"允许"。',
        confirmText: '继续',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            try {
              // 请求权限
              const permissions = [
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
              ]
              
              // 使用plus.android.requestPermissions
              plus.android.requestPermissions(permissions, (resultObj) => {
                console.log('权限申请结果:', resultObj)
                
                let hasAllPermissions = true
                if (resultObj.deniedAlways && resultObj.deniedAlways.length > 0) {
                  hasAllPermissions = false
                } else if (resultObj.deniedPresent && resultObj.deniedPresent.length > 0) {
                  hasAllPermissions = false
                }
                
                if (hasAllPermissions) {
                  console.log('存储权限获取成功')
                  // 保存权限状态
                  uni.setStorageSync('storage_permission_granted', true)
                  callback(true)
                } else {
                  console.log('存储权限被拒绝')
                  uni.setStorageSync('storage_permission_granted', false)
                  uni.showModal({
                    title: '权限被拒绝',
                    content: '没有存储权限将无法保存文件到指定目录。\\n\\n您可以在设置中手动开启权限。',
                    confirmText: '知道了',
                    showCancel: false
                  })
                  callback(false)
                }
              }, (error) => {
                console.log('权限申请异常:', error)
                uni.setStorageSync('storage_permission_granted', false)
                callback(false)
              })
              
            } catch (requestError) {
              console.log('请求权限异常:', requestError)
              uni.setStorageSync('storage_permission_granted', false)
              callback(false)
            }
          } else {
            console.log('用户取消权限申请')
            uni.setStorageSync('storage_permission_granted', false)
            callback(false)
          }
        }
      })
      
    } catch (error) {
      console.log('权限系统异常:', error)
      uni.setStorageSync('storage_permission_granted', false)
      callback(false)
    }
    // #endif
    
    // #ifndef APP-PLUS
    callback(true)
    // #endif
  }
  
  /**
   * 请求所有文件访问权限（MANAGE_EXTERNAL_STORAGE）
   * @param {Function} callback 权限获取成功回调
   */
  static requestManageExternalStoragePermission(callback) {
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity()
      const Build = plus.android.importClass('android.os.Build')
      const Intent = plus.android.importClass('android.content.Intent')
      const Settings = plus.android.importClass('android.provider.Settings')
      const Context = plus.android.importClass('android.content.Context')
      const ContextCompat = plus.android.importClass('androidx.core.content.ContextCompat')
      const Manifest = plus.android.importClass('android.Manifest')
      
      console.log('Android SDK版本:', Build.VERSION.SDK_INT)
      
      // 只有Android 11+才需要MANAGE_EXTERNAL_STORAGE权限
      if (Build.VERSION.SDK_INT < 30) {
        console.log('Android版本低于11，无需MANAGE_EXTERNAL_STORAGE权限')
        callback(true)
        return
      }
      
      // 检查是否已有MANAGE_EXTERNAL_STORAGE权限
      let hasManagePermission = false
      try {
        // 检查是否有MANAGE_EXTERNAL_STORAGE权限
        hasManagePermission = this.checkManageExternalStoragePermission()
      } catch (permError) {
        console.log('MANAGE_EXTERNAL_STORAGE权限检查失败:', permError)
      }
      
      if (hasManagePermission) {
        console.log('MANAGE_EXTERNAL_STORAGE权限已获取')
        // 保存权限状态
        uni.setStorageSync('manage_external_storage_permission_granted', true)
        callback(true)
        return
      }
      
      // 请求MANAGE_EXTERNAL_STORAGE权限
      console.log('需要请求MANAGE_EXTERNAL_STORAGE权限')
      uni.showModal({
        title: '重要权限申请',
        content: '为了能够更好地管理文件，需要您授予"允许访问所有文件"权限。\\n\\n请在接下来的系统设置中找到并开启此权限。',
        confirmText: '前往设置',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            try {
              // 跳转到应用的所有文件访问权限设置页面
              const intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
              const uri = plus.android.invoke('android.net.Uri', 'parse', 'package:' + main.getPackageName())
              intent.setData(uri)
              main.startActivityForResult(intent, 1001)
              
              // 使用定时器检查权限状态变化
              let checkCount = 0
              const maxCheckCount = 20 // 最多检查20次
              const checkPermissionInterval = setInterval(() => {
                checkCount++
                const currentPermission = this.checkManageExternalStoragePermission()
                console.log('检查权限状态(' + checkCount + '):', currentPermission)
                
                if (currentPermission) {
                  // 权限已获取
                  clearInterval(checkPermissionInterval)
                  console.log('MANAGE_EXTERNAL_STORAGE权限获取成功')
                  uni.setStorageSync('manage_external_storage_permission_granted', true)
                  uni.showToast({
                    title: '权限获取成功',
                    icon: 'success'
                  })
                  callback(true)
                } else if (checkCount >= maxCheckCount) {
                  // 超时未获取权限
                  clearInterval(checkPermissionInterval)
                  console.log('MANAGE_EXTERNAL_STORAGE权限获取超时')
                  uni.setStorageSync('manage_external_storage_permission_granted', false)
                  uni.showModal({
                    title: '权限获取提醒',
                    content: '请确认是否已在设置中开启"允许访问所有文件"权限。\\n\\n如果没有开启，可能导致文件操作受限。',
                    confirmText: '知道了',
                    showCancel: false
                  })
                  callback(false)
                }
              }, 1000) // 每秒检查一次
              
            } catch (requestError) {
              console.log('请求MANAGE_EXTERNAL_STORAGE权限异常:', requestError)
              uni.setStorageSync('manage_external_storage_permission_granted', false)
              callback(false)
            }
          } else {
            console.log('用户取消MANAGE_EXTERNAL_STORAGE权限申请')
            uni.setStorageSync('manage_external_storage_permission_granted', false)
            callback(false)
          }
        }
      })
      
    } catch (error) {
      console.log('MANAGE_EXTERNAL_STORAGE权限系统异常:', error)
      uni.setStorageSync('manage_external_storage_permission_granted', false)
      callback(false)
    }
    // #endif
    
    // #ifndef APP-PLUS
    callback(true)
    // #endif
  }
  
  /**
   * 检查MANAGE_EXTERNAL_STORAGE权限状态
   * @returns {boolean} 是否已获得权限
   */
  static checkManageExternalStoragePermission() {
    try {
      const main = plus.android.runtimeMainActivity()
      const Build = plus.android.importClass('android.os.Build')
      const Environment = plus.android.importClass('android.os.Environment')
      
      // 只有Android 11+才需要检查MANAGE_EXTERNAL_STORAGE权限
      if (Build.VERSION.SDK_INT < 30) {
        return true
      }
      
      // 检查是否有MANAGE_EXTERNAL_STORAGE权限
      return Environment.isExternalStorageManager()
    } catch (error) {
      console.log('检查MANAGE_EXTERNAL_STORAGE权限异常:', error)
      return false
    }
  }
  
  /**
   * 检查是否已获得存储权限
   * @returns {boolean} 是否已获得权限
   */
  static hasStoragePermission() {
    // #ifdef APP-PLUS
    try {
      // 先检查缓存的权限状态
      const cachedPermission = uni.getStorageSync('storage_permission_granted')
      if (cachedPermission !== '') {
        return cachedPermission === true
      }
      
      // 如果没有缓存状态，则实际检查权限
      const main = plus.android.runtimeMainActivity()
      const Context = plus.android.importClass('android.content.Context')
      const ContextCompat = plus.android.importClass('androidx.core.content.ContextCompat')
      const Manifest = plus.android.importClass('android.Manifest')
      const Build = plus.android.importClass('android.os.Build')
      
      // Android 6.0+才需要动态权限
      if (Build.VERSION.SDK_INT < 23) {
        return true
      }
      
      // 检查是否已有权限
      const PERMISSION_GRANTED = 0 // PackageManager.PERMISSION_GRANTED
      let hasWritePermission = false
      let hasReadPermission = false
      
      try {
        hasWritePermission = ContextCompat.checkSelfPermission(main, Manifest.permission.WRITE_EXTERNAL_STORAGE) === PERMISSION_GRANTED
        hasReadPermission = ContextCompat.checkSelfPermission(main, Manifest.permission.READ_EXTERNAL_STORAGE) === PERMISSION_GRANTED
        return hasWritePermission && hasReadPermission
      } catch (permError) {
        console.log('权限检查失败:', permError)
        return false
      }
    } catch (error) {
      console.log('权限检查异常:', error)
      return false
    }
    // #endif
    
    // #ifndef APP-PLUS
    return true
    // #endif
  }
  
  /**
   * 检查是否已获得所有文件访问权限
   * @returns {boolean} 是否已获得权限
   */
  static hasManageExternalStoragePermission() {
    // #ifdef APP-PLUS
    try {
      // 先检查缓存的权限状态
      const cachedPermission = uni.getStorageSync('manage_external_storage_permission_granted')
      if (cachedPermission !== '') {
        return cachedPermission === true
      }
      
      // 如果没有缓存状态，则实际检查权限
      return this.checkManageExternalStoragePermission()
    } catch (error) {
      console.log('MANAGE_EXTERNAL_STORAGE权限检查异常:', error)
      return false
    }
    // #endif
    
    // #ifndef APP-PLUS
    return true
    // #endif
  }
}

export default PermissionManager